//
//  RegisterViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/8/21.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "RegisterViewController.h"
#import "RentVieitor.h"
#import "AFNetworking.h"
#import "LCMD5Tool.h"
#import "StrategyViewController.h"
#import "RichScanViewController.h"

@interface RegisterViewController ()<UITextFieldDelegate>

@end

@implementation RegisterViewController {
    
    MBProgressHUD *HUD;
    UIButton *getButton;
    UIButton *registBtn;
    UIAlertController *alertController;
    NSInteger getcodeTime;
    UIButton *Btn;
    NSString *num;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"用户注册";
    self.view.backgroundColor = [UIColor whiteColor];
    [self creatLeftView];
    [self creatView];
    
}


- (void)creatLeftView {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 64)];
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(15, 20+12, 100,30);
    [leftBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 10, 90)];
    [leftBtn setImage:[UIImage imageNamed:@"箭头左"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:leftBtn];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 20, KWidth-200, 44)];
    label.text = @"注册";
    label.font = [UIFont systemFontOfSize:17];
    label.textColor = [Utils colorConvertFromString:@"#333333"];
    [view addSubview:label];
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:view];
    
    
}

- (void)creatView {
    
    NSArray *plaArray = @[@"请输入手机号",@"请输入验证码",@"请输入密码(最少8位,字母+数字)"];
    for (int i=0; i<plaArray.count; i++) {
        
        UITextField *numText = [[UITextField alloc] initWithFrame:CGRectMake(20, 20+50*i+5+64, KWidth-40, 40)];
        numText.placeholder = plaArray[i];
        numText.delegate = self;
        numText.tag = 100+i;
        if (i<2) {
            numText.keyboardType = UIKeyboardTypeNumberPad;
        }else {
            numText.secureTextEntry = YES;
        }
       
        numText.font = [UIFont systemFontOfSize:15];
        [self.view addSubview:numText];
        
        CALayer *lineLayer2 = [CALayer layer];
        lineLayer2.backgroundColor = [[UIColor colorWithRed:217/255.0 green:217/255.0 blue:217/255.0 alpha:1] CGColor];
        lineLayer2.frame = CGRectMake(20,20+50*(i+1)+64, KWidth-40, 1);
        [self.view.layer addSublayer:lineLayer2];
        
        if (i == 1) {
            
            getButton = [UIButton buttonWithType:UIButtonTypeSystem];
            getButton.frame = CGRectMake(KWidth-100, 25+64, 80, 40);
            [getButton setTitleColor:[UIColor colorWithRed:99/255.0 green:99/255.0 blue:99/255.0 alpha:1] forState:UIControlStateNormal];
            [getButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            [getButton addTarget:self action:@selector(getNumber) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:getButton];
        }
    }
    
    registBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    registBtn.frame = CGRectMake(20, 20+170+64, KWidth-40, 40);
    [registBtn setBackgroundColor:[UIColor colorWithRed:249/255.0 green:105/255.0 blue:39/255.0 alpha:1]];
    [registBtn setTitle:@"立即注册" forState:UIControlStateNormal];
    [registBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    registBtn.layer.masksToBounds = YES;
    [registBtn addTarget:self action:@selector(rigestAction) forControlEvents:UIControlEventTouchUpInside];
    registBtn.layer.cornerRadius = 2;
    [self.view addSubview:registBtn];
    
    Btn = [UIButton buttonWithType:UIButtonTypeSystem];
    Btn.frame = CGRectMake(20, 20+170+64+60, KWidth-40, 20);
    [Btn setTitle:@"通过扫描分享的二维码注册" forState:UIControlStateNormal];
    [Btn setTitleColor:[Utils colorConvertFromString:@"#666666"] forState:UIControlStateNormal];
    Btn.layer.masksToBounds = YES;
    [Btn addTarget:self action:@selector(saoAction) forControlEvents:UIControlEventTouchUpInside];
    Btn.layer.cornerRadius = 2;
    [self.view addSubview:Btn];

    
}

- (void)saoAction {
    
    RichScanViewController *straVc = [[RichScanViewController alloc] init];
    [straVc returnImgBlock:^(NSString *number) {
        
        [Btn setTitle:@"已扫描(可修改)" forState:UIControlStateNormal];
        num = number;
        
    }];
    [self presentViewController:straVc animated:YES completion:nil];
    
}

//获取验证码
- (void)getNumber {
    
    getButton.enabled = NO;
    UITextField *phoneText = (UITextField *)[self.view viewWithTag:100];
    NSString *request = [self valiMobile:phoneText.text];
    
    //验证手机号码
    if (request != nil) {
        getButton.enabled = YES;
        [APPDELEGATE showPro:@"手机格式不正确"];
        return;
    }
    
    getcodeTime = 60;
    [getButton setTitle:[NSString stringWithFormat:@"%ld",(long)getcodeTime] forState:UIControlStateDisabled];
    
    
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(getCodeBtnTimerOut:) userInfo:nil repeats:YES];
    
    NSString *urlstr= @"http://api2.zuke.com/register/sendsms";
    NSString *md5String = [NSString stringWithFormat:@"%@Zuke.Com.App%@",phoneText.text,urlstr];
    //32位小写
    NSString *phone =  [phoneText.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    md5String = [md5String stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSDictionary *param = @{@"mobile":phone,
                            @"sign":md5String
                            };
    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    manger.requestSerializer.timeoutInterval= 60;
    manger.responseSerializer=[AFHTTPResponseSerializer serializer];
    [manger POST:urlstr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        

        NSDictionary* jsonDic = [NSJSONSerialization
                                 JSONObjectWithData:responseObject
                                 options:kNilOptions
                                 error:nil];
        
        if ([jsonDic[@"code"] isEqualToString:@"10000"]) {
            //发送成功
            [APPDELEGATE showPro:@"验证码已发送"];
            
        }else {
            
            getButton.enabled = YES;
            [APPDELEGATE showPro:jsonDic[@"message"]];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        getButton.enabled = YES;
        [APPDELEGATE showPro:@"网络错误"];
        
    }];
    

    
}


#pragma mark - 时间倒计时
- (void) getCodeBtnTimerOut:(NSTimer *)timer{
    
    getcodeTime--;
    if (getcodeTime > 0) {
        [getButton setTitle:[NSString stringWithFormat:@"%ld",(long)getcodeTime] forState:UIControlStateDisabled];
    }else{
        
        getButton.enabled = YES;
        [getButton setTitle:@"重获验证码" forState:UIControlStateNormal];
        [timer invalidate];
    }
    
}

//注册
- (void)rigestAction {
    
    
    registBtn.enabled = NO;
    UITextField *phone = (UITextField *)[self.view viewWithTag:100];
    UITextField *code = (UITextField *)[self.view viewWithTag:101];
    UITextField *password = (UITextField *)[self.view viewWithTag:102];
    
    //判断填写内容是否完善
    if (phone.text.length == 0 || code.text.length == 0 || password.text.length == 0) {
        
        registBtn.enabled = YES;
        [APPDELEGATE showPro:@"请完善信息"];
        return;
    }
    if (password.text.length < 8) {
        
        registBtn.enabled = YES;
        [APPDELEGATE showPro:@"密码长度必须8位或以上"];
        return;
    }
    
    //判断密码是否合格
    int judge = [self checkIsHaveNumAndLetter:password.text];
    if (judge != 3) {
        
        registBtn.enabled = YES;
        [APPDELEGATE showPro:@"密码只能是字母+数字"];
        return;
    }
    if (num == nil) {
        num = @"";
    }
    
    NSString *urlstr= @"http://api2.zuke.com/register/save";
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@%@%@%@",phone.text,password.text,num,code.text,APPKEY_URL,urlstr];
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSDictionary *param = @{
                            @"mobile":phone.text,
                            @"passwd":password.text,
                            @"smscode":code.text,
                            @"sign":md5String,
                            @"number":num
                            };
    
    __weak typeof(self)weakSelf = self;
    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    manger.responseSerializer=[AFHTTPResponseSerializer serializer];
    manger.requestSerializer.timeoutInterval= 60;
    [manger POST:urlstr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        registBtn.enabled = YES;
        NSDictionary* jsonDic = [NSJSONSerialization
                                 JSONObjectWithData:responseObject
                                 options:kNilOptions
                                 error:nil];
        
        if ([jsonDic[@"code"] isEqualToString:@"10000"]) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"注册成功"
                                                                           message:@"确定现在登录吗?"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                
                                                                      
                //登录成功
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSDictionary *dataDic = jsonDic[@"data"];
                dataDic = [Utils nullDic:dataDic];
                [defaults setObject:dataDic forKey:User_listsKey];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:nil userInfo:nil];
                if ([weakSelf respondsToSelector:@selector(presentingViewController)]) {
                    
                    [weakSelf.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil]; // for IOS 5+
                    
                } else {
                    
                    [weakSelf.parentViewController.parentViewController dismissViewControllerAnimated:YES completion:nil]; // for pre IOS 5
                    
                }

                                                                      
                                                                  }];
            
            UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                //响应事件
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];

                                                                 }];
            
            [alert addAction:defaultAction];
            [alert addAction:cancelAction];  
            [self presentViewController:alert animated:YES completion:nil];
            
        }else {
            
            getButton.enabled = YES;
            [APPDELEGATE showPro:jsonDic[@"message"]];
        
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        registBtn.enabled = YES;
        getButton.enabled = YES;
        [APPDELEGATE showPro:@"网络错误"];
        
    }];
    
}

- (void)backAction {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(int)checkIsHaveNumAndLetter:(NSString*)password{
    //数字条件
    NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    //符合数字条件的有几个字节
    NSUInteger tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:password
                                                                       options:NSMatchingReportProgress
                                                                         range:NSMakeRange(0, password.length)];
    
    //英文字条件
    NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    //符合英文字条件的有几个字节
    NSUInteger tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:password options:NSMatchingReportProgress range:NSMakeRange(0, password.length)];
    
    if (tNumMatchCount == password.length) {
        //全部符合数字，表示沒有英文
        return 1;
    } else if (tLetterMatchCount == password.length) {
        //全部符合英文，表示沒有数字
        return 2;
    } else if (tNumMatchCount + tLetterMatchCount == password.length) {
        //符合英文和符合数字条件的相加等于密码长度
        return 3;
    } else {
        return 4;
        //可能包含标点符号的情況，或是包含非英文的文字，这里再依照需求详细判断想呈现的错误
    }
    
}

//验证手机号
- (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return @"手机号长度只能是11位";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        }else{
            return @"请输入正确的电话号码";
        }
    }
    return nil;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

@end
